<?php

//数据库操作文件

function db_connect($db_name='p802',$host='127.0.0.1',$db_user='root',$db_pwd='root',$charset='utf8'){

    $link = mysqli_connect($host,$db_user,$db_pwd,$db_name);
   
    if(!$link){

        echo '<script>alert("数据库链接失败");history.go(-1);</script>';die;
        }

         mysqli_query($link,'set_names'.$charset);
  
         return $link;
 
}


//删除
function del($table,$where=array()){


	// print_r($where);die;

	if(is_array($where)){
      $str = implode(',',$where);
      $where = "in ($str)";
	}else{

		$where = "=".$where;
	}

	$sql="delete from `$table` where id $where";

		mysqli_query($GLOBALS['link'],$sql);

	   return mysqli_affected_rows($GLOBALS['link']);
}
//删除2
function del2($table,$where){

	// echo '<script>alert("我准备被你删了");location.href="http://www.baidu.com";</script>';

	$where = "=".$where;

	$sql="delete from `$table` where member_id $where";

	mysqli_query($GLOBALS['link'],$sql);

}
//修改
function edit($table,$where,$data){
	$field='';
	foreach($data as $k=>$v){
		$field.="`$k` = '$v',";
	}
	$field = substr($field,0,-1);

	//编写更新编辑的sql语句
	$sql = "update `$table` set $field where `id`=$where";

	// 执行sql语句
    mysqli_query($GLOBALS['link'],$sql);

	return mysqli_affected_rows($GLOBALS['link']);
}

//添加
function add($table,$where=array()){

	    $v   = "'".implode("','",array_values($where))."'";//组装值
	    $key = "`".implode("`,`",array_keys($where))."`";//组装字段

		$sql = "insert into `$table`($key)values($v)";

		// 执行sql语句
		mysqli_query($GLOBALS['link'],$sql);

	   return mysqli_affected_rows($GLOBALS['link']);
}

//查询一条
function getselectByone($table,$where,$field='*'){

	if(is_array($where)){
	  $str = '';
	  $i = 0;
      foreach($where as $k=>$v){
      	//如果循环到最后一次则不拼接and
      	if($i==count($where)-1){

      		$str .= "`$k` = '$v'";//username =1 and password =2
      	}else{
      		$str .= "`$k` = '$v' and ";//username =1 and
      	}
      	$i++;
      }
      $where = $str;
	}
    
	$sql = "select $field from `$table` where $where limit 1";

	$result = mysqli_query($GLOBALS['link'],$sql);

	return mysqli_fetch_assoc($result);
}

//查询多条
function getselect($table,$where = 1,$order='',$limit='',$field='*'){

    $where1='';
    if(!empty($limit)){
        $where1.="limit $limit ";
    }
	if(!empty($order)){

		$where1.= 'order by '.$order;
	}

	$sql = "select $field from `$table` where $where $where1";

	$result = mysqli_query($GLOBALS['link'],$sql);

	while($arr = mysqli_fetch_assoc($result)){
		$data[] = $arr;
    }

    return $data;
}